package com.lz.ccjdemo.act;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.lz.ccjdemo.R;
import com.lz.ccjdemo.view.CirclePercentView;

/**
 * 圆形倒计时
 */
public class CirclePercentActivity extends Activity {
    CirclePercentView percentView;
    TextView tvTime;

    int max = 1000;
    long progress = 0;
    Handler handler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circle_percent);
        percentView = findViewById(R.id.progress_circle);
        tvTime = findViewById(R.id.tv_time);
        percentView.setMax(max);
        percentView.setPercentage(progress);
    }

    public void clickStartTimer(View view) {
        tvTime.setText("0%");
        startTimer();
    }

    Runnable runnable;

    private void startTimer() {
        if (handler == null) {
            handler = new Handler();
        }
        if (runnable != null) {
            handler.removeCallbacks(runnable);
            progress=0;
        }
        loadTimer();
    }

    private void loadTimer() {
        if (progress >= max) {
            return;
        }
        handler.postDelayed(runnable = new Runnable() {
            @Override
            public void run() {
                percentView.setPercentage(progress++);
                long pro = (max-progress);
                tvTime.setText(""+pro);
                loadTimer();
            }
        }, 100);
    }

    public String point2(String value) {
        //转换小数点
        if (TextUtils.isEmpty(value)) return "0.00";

        int index = value.indexOf(".");
        if (index == -1) return value;

        String ed = value.substring(index, value.length() > index + 3 ? index + 3 : value.length());
        if (".00".equals(ed) || ".0".equals(ed)) {
            ed = "";
        } else if ("0".equals(ed.substring(ed.length() - 1))) {
            ed = ed.substring(0, ed.length() - 1);
        }
        return value.substring(0, index) + ed;
    }
}
